package com.qyhl.webtv.module_broke.scoop.itemview;

import android.app.Activity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.ScoopListBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_broke.R;
import com.qyhl.webtv.module_broke.utils.radiobutton.MediaManager;
import com.zhy.adapter.recyclerview.base.ItemViewDelegate;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * Created by qyhl on 2017/12/12.
 */

public class ScoopVideoViewDelegete implements ItemViewDelegate<ScoopListBean>, ScoopItemContract.ScoopItemView {
    private boolean isMain;//是否是全部话题
    private Activity activity;

    public final static String TAG = "SCV";

    private ScoopItemPresenter mPresenter;
    private boolean isNeedRefresh;
    private RequestOptions apply;

    public ScoopVideoViewDelegete(boolean isMain, Activity activity, boolean isNeedRefresh) {
        this.isMain = isMain;
        this.activity = activity;
        this.isNeedRefresh = isNeedRefresh;
        mPresenter = new ScoopItemPresenter(this);
        apply = new RequestOptions().error(R.drawable.video_list_portrait_default).placeholder(R.drawable.video_list_portrait_default);
    }

    public ScoopVideoViewDelegete(boolean isMain, Activity activity) {
        this.isMain = isMain;
        this.activity = activity;
        mPresenter = new ScoopItemPresenter(this);
        apply = new RequestOptions().error(R.drawable.video_list_portrait_default).placeholder(R.drawable.video_list_portrait_default);
    }

    public void setMain(boolean main) {
        isMain = main;
    }

    @Override
    public int getItemViewLayoutId() {
        return R.layout.broke_item_scoop_video;
    }

    @Override
    public boolean isForViewType(ScoopListBean item, int position) {
        if (item.getBrokeNews().getType() == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void convert(ViewHolder holder, final ScoopListBean bean, int position) {
        //设置用户信息
        ImageView headIcon = holder.getView(R.id.head_icon);

        TextView nickName = holder.getView(R.id.nickname);

        if (bean.getBrokeNews().getIsAnonymous() == 0) {
            Glide.with(activity)
                    .load(R.drawable.scoop_head_default)
                    .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                    .into(headIcon);

            nickName.setText("匿名用户");
        } else {
            Glide.with(activity)
                    .load(bean.getBrokeNews().getCreatorAvatar())
                    .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default).transform(new GlideCircleTransform(activity)))
                    .into(headIcon);
            nickName.setText(bean.getBrokeNews().getAuthor());
        }

        //设置地理位置
        TextView location = holder.getView(R.id.location);
        if (StringUtils.isEmpty(bean.getBrokeNews().getAddress())) {
            location.setVisibility(View.GONE);
        } else {
            location.setVisibility(View.VISIBLE);
            location.setText(bean.getBrokeNews().getAddress());
        }

        //设置时间
        TextView date = holder.getView(R.id.publish_date);
        date.setText(DateUtils.mTranslateDate(bean.getBrokeNews().getPublishtime()));//发布日期设置

        //标题混排设置
        TextView title = holder.getView(R.id.title);
        title.setHighlightColor(activity.getResources().getColor(R.color.Transparent));
        if (StringUtils.isNotEmpty(bean.getBrokePlate().getName()) || StringUtils.isNotEmpty(bean.getBrokeNews().getTitle())) {
            title.setVisibility(View.VISIBLE);
            title.setTag(bean);
            if (isMain) {
                String tagStr = "#" + bean.getBrokePlate().getName() + "#";
                String titleStr = bean.getBrokeNews().getTitle();
                if ((titleStr.length() + tagStr.length()) > 40) {
                    titleStr = titleStr.substring(0, (40 - tagStr.length()));
                    titleStr = titleStr + "...";
                }
                SpannableString styledText = new SpannableString(tagStr + " " + titleStr);
                styledText.setSpan(new TextAppearanceSpan(activity, R.style.broke_scoop_tag), 0, tagStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                styledText.setSpan(new Clickable(clickListener), 0, tagStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                styledText.setSpan(new Clickable(clickListener2), tagStr.length() + 1, styledText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                if (StringUtils.isNotEmpty(titleStr)) {
                    styledText.setSpan(new TextAppearanceSpan(activity, R.style.broke_scoop_title), tagStr.length(), styledText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                }
                title.setText(styledText);
                title.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
                title.setFocusable(false);//防止抢占了焦点,onItemClick 无效
            } else {
                String mTitle = bean.getBrokeNews().getTitle();
                if (mTitle.length() > 35) {
                    mTitle = mTitle.substring(0, 35);
                    mTitle = mTitle + "...";
                }
                SpannableString spannableTitle = new SpannableString(mTitle);
                spannableTitle.setSpan(new TextAppearanceSpan(activity, R.style.broke_scoop_title), 0, spannableTitle.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableTitle.setSpan(new Clickable(clickListener2), 0, spannableTitle.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                title.setText(spannableTitle);
                title.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
                title.setFocusable(false);
            }
        } else {
            title.setVisibility(View.GONE);
        }

        //设置摘要
        TextView summary = holder.getView(R.id.summary);
        if (StringUtils.isEmpty(bean.getBrokeNews().getContent())) {
            summary.setVisibility(View.GONE);
        } else {
            summary.setVisibility(View.VISIBLE);
            summary.setText(bean.getBrokeNews().getContent());
        }

        //关注状态设置
        final LikeButton likeBtn = holder.getView(R.id.like_btn);
        TextView likeNum = holder.getView(R.id.like_num);

        int follows = bean.getAttention();//关注人数

        if (bean.getIsAttention() == 0) {//初始化关注状态
            setNormal(likeNum, likeBtn, follows);
        } else {
            setChecked(likeNum, likeBtn, follows);
        }

        likeBtn.setEnabled(true);
        likeBtn.setTag(bean);
        likeBtn.setTag(R.id.like_num, likeNum);
        //关注监听
        likeBtn.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(final LikeButton likeButton) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            TextView num = (TextView) likeButton.getTag(R.id.like_num);
                            ScoopListBean bean = (ScoopListBean) likeButton.getTag();
                            bean.setAttention(bean.getAttention() + 1);
                            setChecked(num, likeBtn, bean.getAttention());
                            mPresenter.addAttention(bean.getBrokeNews().getId() + "");
                        } else {
                            likeBtn.setLiked(false);
                            Toasty.normal(activity, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                            RouterManager.routerLogin(activity, 300);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

            }

            @Override
            public void unLiked(final LikeButton likeButton) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            TextView num = (TextView) likeButton.getTag(R.id.like_num);
                            ScoopListBean bean = (ScoopListBean) likeButton.getTag();
                            bean.setAttention(bean.getAttention() - 1);
                            setNormal(num, likeBtn, bean.getAttention());
                            mPresenter.cancelAttention(bean.getBrokeNews().getId() + "");
                        } else {
                            likeBtn.setLiked(true);
                            Toasty.normal(activity, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                            RouterManager.routerLogin(activity, 300);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

            }
        });

        //设置处理状态
        TextView state_text = holder.getView(R.id.state_text);
        ImageView state_icon = holder.getView(R.id.state_icon);
        switch (bean.getBrokeNews().getStatus()) {
            case 2://未处理
                state_icon.setVisibility(View.GONE);
                state_text.setVisibility(View.GONE);
                break;
            case 21://处理中
                state_icon.setVisibility(View.VISIBLE);
                state_text.setVisibility(View.VISIBLE);
                state_text.setText("处理中");
                state_text.setTextColor(activity.getResources().getColor(R.color.global_base));
                state_icon.setImageResource(R.drawable.scoop_disposing);
                break;
            case 22://已处理
                state_icon.setVisibility(View.VISIBLE);
                state_text.setVisibility(View.VISIBLE);
                state_text.setText("已处理");
                state_text.setTextColor(activity.getResources().getColor(R.color.scoop_disposed));
                state_icon.setImageResource(R.drawable.scoop_disposed);
                break;
            case 23:
                state_icon.setVisibility(View.GONE);
                state_text.setVisibility(View.GONE);
                break;
            default:
                break;
        }

        ImageView videoCover = holder.getView(R.id.video_cover);
        ViewGroup.LayoutParams params = videoCover.getLayoutParams();
        if (bean.getVideoCoverWidth() > bean.getVideoCoverHeight()) {
            params.width = (bean.getVideoCoverWidth() > 600 || bean.getVideoCoverWidth() <= 0) ? 600 : bean.getVideoCoverWidth();
            params.height = params.width * 9 / 16;
        } else {
            params.height = (bean.getVideoCoverHeight() > 600 || bean.getVideoCoverHeight() <= 0) ? 600 : bean.getVideoCoverHeight();
            params.width = params.height * 9 / 16;
        }
        videoCover.setLayoutParams(params);
        Glide.with(activity).load(bean.getBrokeNews().getCoverImgUrl()).apply(apply).into(videoCover);

        RelativeLayout videoLayout = holder.getView(R.id.video_layout);
        videoLayout.setTag(bean);
        videoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScoopListBean bean = (ScoopListBean) v.getTag();
                MediaManager me = MediaManager.getIntance();
                if (me.isPlay()) {
                    me.release();
                    me.getTextView().endAnimation();
                    //恢复时间
                    me.getTextView().setContent(me.getContentBean().getBrokeNews().getAudioDuration());
                }
                Bundle bundle = new Bundle();
                bundle.putString(IntentKey_VideoUrl,bean.getBrokeNews().getUrl());
                bundle.putString(IntentKey_VideoCover,bean.getBrokeNews().getCoverImgUrl());
                RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL,bundle);
            }
        });

    }

    //textview局部点击事件处理
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScoopListBean bean = (ScoopListBean) v.getTag();
            Bundle bundle = new Bundle();
            bundle.putString("id", bean.getBrokePlate().getId() + "");
            bundle.putString("title", bean.getBrokePlate().getName());
            RouterManager.router(ARouterPathConstant.SCOOP_TOPIC, bundle);
        }
    };

    //textview局部点击事件处理
    private View.OnClickListener clickListener2 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScoopListBean bean = (ScoopListBean) v.getTag();
            Bundle bundle = new Bundle();
            bundle.putString("id", bean.getBrokeNews().getId()+"");
            RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT, bundle);
        }
    };

//    /**
//     * 关注成功
//     *
//     * @param likeNum
//     * @param likeBtn
//     */
//    @Override
//    public void addSuccess(TextView likeNum, LikeButton likeBtn, ScoopListBean scoopListBean) {
//        setChecked(likeNum, likeBtn, scoopListBean.getAttention() + 1);
//        scoopListBean.setAttention(scoopListBean.getAttention() + 1);
//        likeBtn.setEnabled(true);
//        if (!MyConfig.userName.equals(scoopListBean.getBrokeNews().getCreator())) {
//            PushTools.BindTag("BrokeNews_" + MyConfig.SITE_ID + "_" + scoopListBean.getBrokeNews().getId());
//        }
//    }
//
//    /**
//     * 关注失败
//     *
//     * @param msg
//     * @param likeNum
//     * @param likeBtn
//     */
//    @Override
//    public void addError(String msg, TextView likeNum, LikeButton likeBtn, ScoopListBean scoopListBean) {
//        Toasty.error(activity, msg, Toast.LENGTH_SHORT, true).show();
//        setNormal(likeNum, likeBtn, scoopListBean.getAttention());
//        likeBtn.setEnabled(true);
//    }
//
//    /**
//     * 取消关注成功
//     *
//     * @param likeNum
//     * @param likeBtn
//     */
//    @Override
//    public void cancelSuccess(TextView likeNum, LikeButton likeBtn, ScoopListBean scoopListBean) {
//        setNormal(likeNum, likeBtn, scoopListBean.getAttention() - 1);
//        scoopListBean.setAttention(scoopListBean.getAttention() - 1);
//        likeBtn.setEnabled(true);
//        if (isNeedRefresh) {
//            BusFactory.getBus().post(new Event.refreshMessage(scoopListBean));
//        }
//        PushTools.unBindTag("BrokeNews_" + MyConfig.SITE_ID + "_" + scoopListBean.getBrokeNews().getId());
//    }
//
//    /**
//     * 取消关注失败
//     *
//     * @param msg
//     * @param likeNum
//     * @param likeBtn
//     */
//    @Override
//    public void cancelError(String msg, TextView likeNum, LikeButton likeBtn, ScoopListBean scoopListBean) {
//        Toasty.error(activity, msg, Toast.LENGTH_SHORT, true).show();
//        setChecked(likeNum, likeBtn, scoopListBean.getAttention());
//        likeBtn.setEnabled(true);
//    }

    /**
     * 设置关注状态
     */
    private void setChecked(TextView likeNum, LikeButton likeBtn, int follow) {
        likeNum.setText(StringUtils.transformNum(follow + "") + "人关注");//设置关注人数
        likeBtn.setLiked(true);
        likeNum.setTextColor(activity.getResources().getColor(R.color.global_base));
    }

    /**
     * 设置未关注状态
     */
    private void setNormal(TextView likeNum, LikeButton likeBtn, int follow) {
        likeNum.setText(StringUtils.transformNum(follow + "") + "人关注");//设置关注人数
        likeBtn.setLiked(false);
        likeNum.setTextColor(activity.getResources().getColor(R.color.global_gray_lv2));
    }


    /**
     * 混排局部点击事件
     */
    class Clickable extends ClickableSpan {
        private View.OnClickListener mListener;

        public Clickable(View.OnClickListener l) {
            mListener = l;
        }

        /**
         * 重写父类点击事件
         */
        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        /*
         *重写父类updateDrawState方法  我们可以给TextView设置字体颜色,背景颜色等等...
         */
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);//取消下划线
        }

    }


}
